package com.lvideo.http;

import android.content.Context;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;

/**
 * Author: liuxiaojiang(liuxiaojiang@lvideo.com)
 * Date: 2016-02-18
 * Time: 18:00
 * Description: 用于https证书的验证
 */
public class TrustSSLSocketFactory{
    private static final String KEY_STORE_TYPE_P12 = "PKCS12";
    private static final String keyStoreFileName = "secret.html";
    private static final String keyStorePassword = "!@c135246";

    public static KeyManager[] createKeyManagers(Context pContext)
            throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
        if(pContext == null){
           return null;
        }
        InputStream inputStream = pContext.getResources().getAssets().open(keyStoreFileName);
        KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12);
        keyStore.load(inputStream, keyStorePassword.toCharArray());

        KeyManager[] managers = null;

        KeyManagerFactory keyManagerFactory =
                KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword == null ? null : keyStorePassword.toCharArray());
        managers = keyManagerFactory.getKeyManagers();
        if(inputStream != null){
            inputStream.close();
        }

        return managers;
    }
}
